<template>
  <el-form
    ref="copyrightInfoFormRef"
    :inline="true"
    :model="copyrightInfoData"
    :rules="formCopyright"
    class="-mb-15px"
    label-width="130px"
  >
    <el-descriptions
      class="margin-top"
      title="数字版权合同信息（必填）"
      :column="2"
      size="default"
      border
    >
      <el-descriptions-item span="2">
        <template #label>
          <div class="cell-item">
            <el-form-item label="合同名称:" prop="contractName">
              <el-input
                v-model="copyrightInfoData.contractName"
                class="!w-240px"
                clearable
                placeholder="请输入合同名称"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="合同签订时间:" prop="copyrightSignTime">
              <el-date-picker
                v-model="copyrightInfoData.copyrightSignTime"
                type="datetime"
                placeholder="选择时间"
              />
            </el-form-item>
          </div>
        </template>
      </el-descriptions-item>
      <el-descriptions-item span="2">
        <template #label>
          <div class="cell-item">
            <el-form-item label="合同编号:" prop="contractNumber">
              <el-input
                v-model="copyrightInfoData.contractNumber"
                class="!w-240px"
                clearable
                placeholder="请输入合同编号"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="项目编号:" prop="projectNumber">
              <el-input
                v-model="copyrightInfoData.projectNumber"
                class="!w-240px"
                clearable
                placeholder="请输入项目编号"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </div>
        </template>
      </el-descriptions-item>
      <el-descriptions-item span="2">
        <template #label>
          <div class="cell-item">
            <el-form-item label="资金总额(元):" prop="amount">
              <el-input-number
                v-model="copyrightInfoData.amount"
                class="!w-240px"
                clearable
                placeholder="请输入资金总额"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="发票类型:" prop="invoice">
              <el-radio-group v-model="copyrightInfoData.invoice" class="!w-240px">
                <el-radio label="0" size="large">纸质普票</el-radio>
                <el-radio label="1" size="large">专用发票</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </template>
      </el-descriptions-item>
      <el-descriptions-item span="2">
        <template #label>
          <div class="cell-item">
            <el-form-item label="资金结算方式:" prop="fundSettle">
              <el-radio-group v-model="copyrightInfoData.fundSettle" class="!w-240px">
                <el-radio label="0" size="large">一次性结算</el-radio>
                <el-radio label="1" size="large">分阶段结算</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </template>
      </el-descriptions-item>
      <el-descriptions-item span="2" v-if="copyrightInfoData.fundSettle == '1'">
        <template #label>
          <div class="cell-item">
            <el-form-item>
              <el-button plain type="primary" @click="onAddItemStage()">
                <Icon class="mr-5px" icon="ep:plus" />
                添加阶段
              </el-button>
            </el-form-item>
            <el-table
              :data="stagesList"
              style="width: 100%"
              max-height="250"
              :cell-style="{ height: '60px' }"
              v-if="copyrightInfoData.fundSettle == '1'"
            >
              <el-table-column prop="stage" label="阶段" />
              <el-table-column prop="expires" label="期限(天)">
                <template #default="scope">
                  <input
                    type="text"
                    v-model="scope.row.expires"
                    class="ipt"
                    style="min-width: 60px"
                    @blur="iptBlur(scope.row, $event)"
                  />
                  <span>天</span>
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="结算金额(元)">
                <template #default="scope">
                  <input
                    type="text"
                    v-model="scope.row.amount"
                    class="ipt"
                    style="min-width: 60px"
                    @blur="iptBlur(scope.row, $event)"
                  /><span>元</span>
                </template>
              </el-table-column>
              <el-table-column prop="percentum" label="占总额百分比(%)">
                <template #default="scope">
                  <input
                    type="text"
                    v-model="scope.row.percentum"
                    class="ipt"
                    style="min-width: 60px"
                    @blur="iptBlur(scope.row, $event)"
                  /><span>%</span>
                </template>
              </el-table-column>
              <el-table-column prop="states" label="付款状态">
                <template #default="{ row }">
                  <el-select v-model="row.states" placeholder="付款状态" style="width: 130px">
                    <el-option
                      v-for="item in stateOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="date" label="付款日期">
                <template #default="{ row }">
                  <el-date-picker
                    v-model="row.date"
                    type="date"
                    placeholder="付款日期"
                    style="width: 130px"
                  />
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="120">
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click.prevent="deleteRowStage(scope.$index)"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-descriptions-item>
      <el-descriptions-item span="2">
        <template #label>
          <div class="cell-item">
            <el-form-item label="合同附件:" prop="fileList">
              <template #default="">
                <el-upload
                  v-if="!appendixButton"
                  ref="upload"
                  class="upload-demo"
                  :http-request="saveFileUpload"
                  multiple="true"
                  :show-file-list="true"
                  :accept="formatFile"
                  :before-upload="beforeAvatarUpload"
                  drag
                  style="width: 500px"
                >
                  <el-icon class="el-icon--upload">
                    <upload-filled />
                  </el-icon>
                  <div class="el-upload__text"> 拖拽文件或 <em> 点击上传 </em></div>
                  <div class="el-upload__tip">
                    支持格式：pdf，word，xlsx，doc，docx，xml，文件大小不超过1024M
                  </div>
                </el-upload>
                <el-button v-if="appendixButton" plain type="primary" @click="appendixPreview()">
                  <Icon class="mr-5px" icon="ep:search" />
                  预览附件
                </el-button>
              </template>
            </el-form-item>
          </div>
        </template>
      </el-descriptions-item>
    </el-descriptions>
    <el-divider />
    <div class="div-info">
      <div class="div-A inline-div">
        <el-form-item>
          <span><h3>甲方信息</h3></span>
        </el-form-item>
        <br />
        <el-form-item label="甲方:" prop="methName">
          <el-input
            v-model="copyrightInfoData.methName"
            class="!w-240px"
            clearable
            placeholder="请输入甲方"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="甲方法人:" prop="methCorp">
          <el-input
            v-model="copyrightInfoData.methCorp"
            class="!w-240px"
            clearable
            placeholder="请输入甲方法人"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="甲方联系人:" prop="methContact">
          <el-input
            v-model="copyrightInfoData.methContact"
            class="!w-240px"
            clearable
            placeholder="请输入甲方联系人"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="甲方通讯录地址:" prop="methMail">
          <el-input
            v-model="copyrightInfoData.methMail"
            class="!w-240px"
            clearable
            placeholder="请输入甲方通讯录地址"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="甲方账号名称:" prop="methAccount">
          <el-input
            v-model="copyrightInfoData.methAccount"
            class="!w-240px"
            clearable
            placeholder="请输入甲方账号名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="甲方账号:" prop="methAccountNumber">
          <el-input
            v-model="copyrightInfoData.methAccountNumber"
            class="!w-240px"
            clearable
            placeholder="请输入甲方账号"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="甲方开户银行:" prop="methOpeningBank">
          <el-input
            v-model="copyrightInfoData.methOpeningBank"
            class="!w-240px"
            clearable
            placeholder="请输入甲方开户银行"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      </div>
      <el-divider direction="vertical" />
      <div class="div-B inline-div">
        <el-form-item>
          <span><h3>乙方信息</h3></span>
        </el-form-item>
        <br />
        <el-form-item label="乙方:" prop="ethName">
          <el-input
            v-model="copyrightInfoData.ethName"
            class="!w-240px"
            clearable
            placeholder="请输入乙方"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="乙方法人:" prop="ethCorp">
          <el-input
            v-model="copyrightInfoData.ethCorp"
            class="!w-240px"
            clearable
            placeholder="请输入乙方法人"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="乙方联系人:" prop="ethContact">
          <el-input
            v-model="copyrightInfoData.ethContact"
            class="!w-240px"
            clearable
            placeholder="请输入乙方联系人"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="乙方通讯录地址:" prop="ethMail">
          <el-input
            v-model="copyrightInfoData.ethMail"
            class="!w-240px"
            clearable
            placeholder="请输入乙方通讯录地址"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="乙方账号名称:" prop="ethAccount">
          <el-input
            v-model="copyrightInfoData.ethAccount"
            class="!w-240px"
            clearable
            placeholder="请输入乙方账号名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="乙方账号:" prop="ethAccountNumber">
          <el-input
            v-model="copyrightInfoData.ethAccountNumber"
            class="!w-240px"
            clearable
            placeholder="请输入乙方账号"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="乙方开户银行:" prop="ethOpeningBank">
          <el-input
            v-model="copyrightInfoData.ethOpeningBank"
            class="!w-240px"
            clearable
            placeholder="请输入乙方开户银行"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      </div>
    </div>
    <br />
    <el-divider />
    <el-form-item v-if="PropButton">
      <el-button plain type="primary" @click="onAddItemProp()">
        <Icon class="mr-5px" icon="ep:plus" />
        添加第三方
      </el-button>
    </el-form-item>
    <div class="div-C inline-div" v-if="PropInfo">
      <el-form-item>
        <span><h3>第三方信息</h3></span>
      </el-form-item>
      <br />
      <el-form-item label="第三方名称:" prop="propName">
        <el-input
          v-model="copyrightInfoData.propName"
          class="!w-240px"
          clearable
          placeholder="请输入第三方名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="第三方法人:" prop="propCorp">
        <el-input
          v-model="copyrightInfoData.propCorp"
          class="!w-240px"
          clearable
          placeholder="请输入第三方法人"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="第三方联系人:" prop="propContact">
        <el-input
          v-model="copyrightInfoData.propContact"
          class="!w-240px"
          clearable
          placeholder="请输入第三方联系人"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="第三方通讯地址:" prop="propMail">
        <el-input
          v-model="copyrightInfoData.propMail"
          class="!w-240px"
          clearable
          placeholder="请输入通讯地址"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="第三方账号名称:" prop="propAccount">
        <el-input
          v-model="copyrightInfoData.propAccount"
          class="!w-240px"
          clearable
          placeholder="请输入账号名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="第三方账号:" prop="propAccountNumber">
        <el-input
          v-model="copyrightInfoData.propAccountNumber"
          class="!w-240px"
          clearable
          placeholder="请输入账号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="第三方开户银行:" prop="propOpeningBank">
        <el-input
          v-model="copyrightInfoData.propOpeningBank"
          class="!w-240px"
          clearable
          placeholder="请输入开户银行"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
    </div>
    <br />
    <el-divider />
    <span><h3>数字资源版权信息</h3></span>
    <el-form-item label="资源名称:" prop="name">
      <el-input
        v-model="copyrightInfoData.name"
        class="!w-240px"
        clearable
        :disabled="disabled"
        placeholder="请输入资源名称"
      />
    </el-form-item>

    <el-form-item label="资源类型:" prop="type">
      <el-input
        v-model="copyrightInfoData.type"
        class="!w-240px"
        clearable
        :disabled="disabled"
        placeholder="请输入资源类型"
      />
    </el-form-item>
    <br />
    <el-form-item label="版权编号:" prop="copyrightNumber">
      <el-input
        v-model="copyrightInfoData.copyrightNumber"
        class="!w-240px"
        clearable
        :disabled="disabled"
        placeholder="请输入版权编号"
      />
    </el-form-item>

    <el-form-item label="著作权人:" prop="copyrightAuthor">
      <el-input
        v-model="copyrightInfoData.copyrightAuthor"
        class="!w-240px"
        clearable
        :disabled="disabled"
        placeholder="请输入著作权人"
      />
    </el-form-item>
    <br />
    <el-form-item label="版权期限:" prop="validity">
      <el-radio-group v-model="copyrightInfoData.validity" class="!w-240px">
        <el-radio label="0" size="large">{{ validitys.always }}</el-radio>
        <el-radio label="1" size="large">{{ validitys.notAlways }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="选择时间:" prop="time" v-if="copyrightInfoData.validity == '1'">
      <el-date-picker
        v-model="copyrightInfoData.datetime"
        type="daterange"
        start-placeholder="请选择开始日期"
        end-placeholder="请选择结束日期"
        class="!w-260px"
        @change="handelChangeTime"
      />
    </el-form-item>
    <el-divider />
    <span><h3>资源信息(必填)</h3></span>
    <el-form-item>
      <el-button plain type="primary" @click="onAddItem()">
        <Icon class="mr-5px" icon="ep:plus" />
        添加资源
      </el-button>
    </el-form-item>
    <br />
    <el-tabs type="border-card" @tab-click="selectTab" :model-value="activeName">
      <el-tab-pane label="图书库" name="42">
        <ContentWrap>
          <el-table v-loading="ResourceLoading" :data="mateList.list">
            <el-table-column type="selection" width="55" />
            <el-table-column
              v-for="(column, index) in mateList.columns"
              :key="index"
              :prop="column.prop"
              :label="column.label"
              align="center"
            >
              <template #default="scope">
                <el-image
                  v-if="imaged(scope.row[column.prop])"
                  :src="buildImage(column.prop, scope.row)"
                  style="max-width: 50px"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><icon-picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="status" label="资源状态">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.RESOURCE_STATUS" :value="scope.row.status" />
              </template>
            </el-table-column>
          </el-table>
        </ContentWrap>
      </el-tab-pane>
      <el-tab-pane label="图片库" name="picture">
        <ContentWrap>
          <el-table
            v-loading="ResourceLoading"
            :data="pictureList.list"
            :show-overflow-tooltip="true"
            :stripe="true"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column align="center" prop="url" label="图片">
              <template #default="{ row }">
                <el-image :src="row.url" style="max-width: 100px" @click="imagePreview(row.url)" />
              </template>
            </el-table-column>
            <el-table-column align="center" prop="name" label="名称" />
            <el-table-column align="center" prop="size" label="尺寸" />
            <el-table-column align="center" prop="format" label="格式" />
            <el-table-column align="center" prop="fileSize" label="大小" />
            <el-table-column align="center" prop="createTime" label="创建时间" />
          </el-table>
        </ContentWrap>
      </el-tab-pane>
      <el-tab-pane label="视频库" name="video">
        <ContentWrap>
          <el-table
            v-loading="ResourceLoading"
            :data="videoList.list"
            :show-overflow-tooltip="true"
            :stripe="true"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column align="left" prop="name" label="名称" width="150" />
            <el-table-column align="center" prop="ext" label="格式" />
            <el-table-column align="left" prop="fileSize" label="大小" width="100" />
            <el-table-column align="center" prop="createTime" label="创建时间" />
          </el-table>
        </ContentWrap>
      </el-tab-pane>
      <!-- <el-tab-pane label="音频库" name="audio" :disabled="audioDisabled"> -->
      <el-tab-pane label="音频库" name="audio">
        <ContentWrap>
          <el-table
            v-loading="ResourceLoading"
            :data="audioList.list"
            :show-overflow-tooltip="true"
            :stripe="true"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column align="left" prop="url" label="音频" width="320">
              <template #default="{ row }">
                <audio :src="row.url" controls></audio>
              </template>
            </el-table-column>
            <el-table-column align="left" prop="name" label="名称" />
            <el-table-column align="center" prop="ext" label="格式" />
            <el-table-column align="left" prop="fileSize" label="大小" width="100" />
            <el-table-column align="center" prop="createTime" label="创建时间" />
          </el-table>
          <!-- <Pagination
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNo"
            :total="videoList.total"
            @pagination="handelQuery('audio')"
          /> -->
        </ContentWrap>
      </el-tab-pane>
    </el-tabs>
  </el-form>
  <div style="text-align: center; margin-top: 40px" class="affix-container">
    <el-affix position="bottom" target=".affix-container">
      <el-button type="primary" @click="submitForm">保存</el-button>
      <el-button type="primary" @click="submitFormClose">保存并关闭</el-button>
      <el-button type="primary" @click="resetForm">重置</el-button>
      <el-button type="primary" @click="router.go(-1)">关闭</el-button>
    </el-affix>
  </div>

  <SelectResource ref="selectResourceRef" @ResourcesListChange="ResourcesListChange" />
</template>
<script lang="ts" setup>
import * as CopyrightApi from '@/api/copyright/copyright'
import type { CopyrightStages } from '@/api/copyright/copyright'
import { type UploadProps, UploadFiles } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import router from '@/router'
import { useRoute } from 'vue-router'
import SelectResource from '@/views/common/SelectResource.vue'
import { DICT_TYPE } from '@/utils/dict'
import * as metaApi from '@/api/meta'
import { isArray } from '@/utils/is'
import { createImageViewer } from '@/components/ImageViewer'
import { FileFormat, FileSize } from '@/utils/config'
import * as resourceApi from '@/api/resource'

defineOptions({ name: 'CoptypeyrightForm' })

const selectResourceRef = ref()
const { t } = useI18n() // 国际化
// const fileList = ref<UploadFiles>([]) //文件列表
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) //弹窗
const disabled = ref(false) // 禁用输入框
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const start = new Date() // 时间选择器-开始日期
const end = new Date() // 时间选择器-结束日期
const validitys = ref({ always: '永久版权', notAlways: '非永久版权' }) // 版权期限
const formDataCopyrightStatus = ref({ normal: '正常', notValidity: '已过期' }) // 版权状态

const activeName = ref('42')
const ResourceLoading = ref(false)
const tempData = ref([]) //临时数据
const mateList = ref([]) // 资源列表图书库
const pictureList = ref([])
const videoList = ref([])
const audioList = ref([])
const resourceList = ref([])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  keyword: null,
  createTime: []
})
/** 切换资源表格tab标签 */
// const selectTab = async (pane, ev) => {
//   let name = pane.props.name
//   await handelQuery(name)
// }
/** 重置资源列表 */
const restTabs = () => {
  if (mateList.value.length == 0) {
    initMateList(activeName.value)
  }
  resourceList.value = []
  pictureList.value = []
  videoList.value = []
  audioList.value = []
  mateList.value.list = []
}
/** 初始化资源图书列表 */
const initMateList = async (name) => {
  mateList.value = await metaApi.selectData(name, queryParams)
  tempData.value = mateList.value.list
  mateList.value.list = []
}
/** 添加资源选中数据 */
const ResourcesListChange = async (list: any, name: string): Promise<void> => {
  ResourceLoading.value = true
  activeName.value = name
  if (name == 'picture') {
    pictureList.value.list = list
  } else if (name == 'video') {
    videoList.value.list = list
  } else if (name == 'audio') {
    audioList.value.list = list
  } else {
    mateList.value.list = list
  }
  ResourceLoading.value = false
}
/** 阶段列表 */
const stagesList = ref<CopyrightStages[]>([
  {
    id: 1,
    stage: '第' + 1 + '阶段',
    expires: '30',
    amount: '10000',
    percentum: '10%',
    states: '0',
    date: '2016-05-01',
    parentId: 0
  }
])
/** 版权表单 */
const copyrightInfoData = ref({
  id: 0, //id
  contractName: '', //合同名称
  copyrightSignTime: '', //签订时间
  contractNumber: '', //合同编号
  projectNumber: '', //项目编号
  amount: '', //资金总额
  invoice: '', //发票类型
  fundSettle: '', //资金结算方式
  // contractFile: [], //合同附件
  appendix: '', //合同附件
  methName: '', //甲方
  methCorp: '', //甲方法人
  methContact: '', //甲方联系人
  methMail: '', //甲方通讯地址
  methAccount: '', //甲方账号名称
  methAccountNumber: '', //甲方账号
  methOpeningBank: '', //甲方开户银行
  ethName: '', //乙方
  ethCorp: '', //乙方法人
  ethContact: '', //乙方联系人
  ethMail: '', //乙方通讯地址
  ethAccount: '', //乙方账号名称
  ethAccountNumber: '', //乙方账号
  ethOpeningBank: '', //乙方开户银行
  propName: '', //三方名称
  propCorp: '', //三方法人
  propContact: '', //三方联系人
  propMail: '', //三方通讯地址
  propAccount: '', //三方账号名称
  propAccountNumber: '', //三方账号
  propOpeningBank: '', //三方开户银行
  name: '', //资源名称
  doi: '', //doi
  type: '', //资源类型
  copyrightNumber: '', //版权编号
  copyrightAuthor: '', //著作权人
  copyrightValidity: '', //版权有效期
  copyrightStatus: '', //版权状态
  validity: '0', //版权期限
  repository: '', //所属库
  datetime: [end, start], //时间日期
  resourceInformationList: [] //
})
/** 重置版权表单 */
const resetForm = () => {
  restTabs()
  copyrightInfoData.value = {
    id: 0, //id
    contractName: '', //合同名称
    copyrightSignTime: '', //签订时间
    contractNumber: '', //合同编号
    projectNumber: '', //项目编号
    amount: '', //资金总额
    invoice: '', //发票类型
    fundSettle: '', //资金结算方式
    // contractFile: [], //合同附件
    appendix: '', //合同附件
    methName: '', //甲方
    methCorp: '', //甲方法人
    methContact: '', //甲方联系人
    methMail: '', //甲方通讯地址
    methAccount: '', //甲方账号名称
    methAccountNumber: '', //甲方账号
    methOpeningBank: '', //甲方开户银行
    ethName: '', //乙方
    ethCorp: '', //乙方法人
    ethContact: '', //乙方联系人
    ethMail: '', //乙方通讯地址
    ethAccount: '', //乙方账号名称
    ethAccountNumber: '', //乙方账号
    ethOpeningBank: '', //乙方开户银行
    propName: '', //三方名称
    propCorp: '', //法人
    propContact: '', //联系人
    propMail: '', //通讯地址
    propAccount: '', //账号名称
    propAccountNumber: '', //账号
    propOpeningBank: '', //开户银行
    name: '', //资源名称
    doi: '', //doi
    type: '', //资源类型
    copyrightNumber: '', //版权编号
    copyrightAuthor: '', //著作权人
    copyrightValidity: '', //版权有效期
    copyrightStatus: '', //版权状态
    validity: '0', //版权期限
    repository: '', //库
    datetime: [end, start], //时间日期
    resourceInformationList: []
  }
  copyrightInfoFormRef.value?.resetFields()
}
/** 表单规则 */
const formCopyright = reactive({
  name: [{ required: true, message: '资源名称不能为空', trigger: 'change' }],
  type: [{ required: true, message: '资源类型不能为空', trigger: 'change' }],
  contractName: [{ required: true, message: '合同名称不能为空', trigger: 'change' }],
  methName: [{ required: true, message: '甲方不能为空', trigger: 'change' }],
  ethName: [{ required: true, message: '乙方不能为空', trigger: 'change' }],
  datetime: [{ required: true, message: '版权期限不能为空', trigger: 'change' }],
  copyrightNumber: [{ required: true, message: '版权编号不能为空', trigger: 'change' }]
})
/** 搜索按钮操作 */
const handleQuery = () => {}
const copyrightInfoFormRef = ref() // 表单 Ref
const PropInfo = ref(false) // 第三方信息 默认隐藏
const PropButton = ref(true) // 第三方按钮 默认显示
/** 添加第三方信息 */
const onAddItemProp = () => {
  PropInfo.value = true
  PropButton.value = false
}
/** 付款状态 */
const stateOptions = [
  {
    value: '0',
    label: '已付款'
  },
  {
    value: '1',
    label: '待付款'
  }
]

/** 上传文件附件 */
const saveFileUpload = async (content) => {
  let form = new FormData()
  form.append('file', content.file)
  const data = await resourceApi.uploadFile(form)
  copyrightInfoData.value.appendix = data.data.previewUrl
}

const formatFile = ref(FileFormat)
//上传前验证文件大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  let size = Number(FileSize)
  if (rawFile.size / 1024 / 1024 > Number(FileSize)) {
    ElMessage.error('file size can not exceed ' + size + 'MB!')
    return false
  }
  return true
}
/** 添加阶段 */
const now = new Date()
const onAddItemStage = () => {
  stagesList.value.push({
    id: 1,
    stage: '第' + (stagesList.value.length + 1) + '阶段',
    expires: '30',
    amount: '10000',
    percentum: '50',
    states: '0',
    date: dayjs(now).format('YYYY-MM-DD'),
    parentId: 0
  })
}
/** 添加资源 */
const onAddItem = async () => {
  selectResourceRef.value.openDialog()
}
//失焦事件，使用事件对象拿到dom元素并进行后续样式的修改
const iptBlur = (value: any, e: any) => {}
/** 移除阶段 */
const deleteRowStage = (index: number) => {
  // handleDelete(list.value[index].id)
  stagesList.value.splice(index, 1)
}
/** 资源版权信息时间修改事件 */
const handelChangeTime = (val: any) => {
  copyrightInfoData.value.datetime = val
}

/** 资源表格修改时重置 */
const restTabsUpdate = () => {
  resourceList.value = []
  pictureList.value = []
  videoList.value = []
  audioList.value = []
}
/** 资源列表 */
const getListCopyrightResources = async () => {
  //重置资源列表
  restTabsUpdate()
  const id = copyrightInfoData.value.id
  const data = await CopyrightApi.getCopyrightResources(id)
  const PictureFiltered = data.filter((item) => item.type === 43)
  const VideoFiltered = data.filter((item) => item.type === 48)
  const AudioFiltered = data.filter((item) => item.type === 51)
  const MateFiltered = data.filter((item) => item.type === 42)
  if (Array.isArray(PictureFiltered) && PictureFiltered.length > 0) {
    const resourceIds = PictureFiltered.map((item) => item.resourceId)
    const list = await CopyrightApi.getPictureList(resourceIds)
    ResourcesListChange(list, 'picture')
  }
  if (Array.isArray(VideoFiltered) && VideoFiltered.length > 0) {
    const resourceIds = VideoFiltered.map((item) => item.resourceId)
    const list = await CopyrightApi.getVideoList(resourceIds)
    ResourcesListChange(list, 'video')
  }
  if (Array.isArray(AudioFiltered) && AudioFiltered.length > 0) {
    const resourceIds = AudioFiltered.map((item) => item.resourceId)
    const list = await CopyrightApi.getAudioList(resourceIds)
    ResourcesListChange(list, 'audio')
  }
  if (Array.isArray(MateFiltered) && MateFiltered.length > 0) {
    const resourceIds = MateFiltered.map((item) => item.resourceId)
    tempData.value
      .filter((item) => resourceIds.includes(item.id))
      .forEach((element) => {
        mateList.value.list.push(element)
      })
  }
}
/** 阶段列表 */
const getListCopyrightStages = async () => {
  const id = copyrightInfoData.value.id
  const data = await CopyrightApi.getCopyrightStages(id)
  stagesList.value = data
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
/** 保存并关闭 */
const submitFormClose = async () => {
  await submitForm()
  router.go(-1)
}
/** 提交表单 */
const submitForm = async () => {
  // 版权状态默认正常 后期检查是否过期
  copyrightInfoData.value.copyrightStatus = formDataCopyrightStatus.value.normal
  // 校验表单
  if (!copyrightInfoFormRef) return
  const valid = await copyrightInfoFormRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    addItemTime(copyrightInfoData.value.validity)
    addResource()
    const copyrightData = copyrightInfoData.value as unknown as CopyrightApi.CopyrightVO
    const resourceData = resourceList.value as unknown as CopyrightApi.CopyrightResource
    const stagesData = stagesList.value as unknown as CopyrightApi.CopyrightStages
    if (type === '新增') {
      const row = await CopyrightApi.CopyrightCount(copyrightInfoData.value.copyrightNumber)
      if (row != 0) {
        return message.info('该版权编号已存在！')
      }
      let data = {
        copyrightData: copyrightData,
        resourceData: resourceData,
        stagesData: stagesData
      }
      await CopyrightApi.createCopyright(data)
      message.success(t('common.createSuccess'))
    } else {
      let data = {
        copyrightData: copyrightData,
        resourceData: resourceData,
        stagesData: stagesData
      }
      await CopyrightApi.updateCopyright(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
/** 新增资源 */
const addResource = async () => {
  let nestedArray = []
  let picture = []
  let video = []
  let audio = []
  let mate = []
  if (pictureList.value.list != undefined) {
    picture = pictureList.value.list.map((item: any) => ({
      ...item,
      type: 43,
      metaId: 43,
      resourceId: item.id
    }))
  }
  if (videoList.value.list != undefined) {
    video = updateResource(48, videoList.value.list)
  }
  if (audioList.value.list != undefined) {
    audio = updateResource(51, audioList.value.list)
  }
  if (mateList.value.list != undefined) {
    mate = mateList.value.list.map((item) => {
      const { fn_cover, ...rest } = item // 使用对象解构来排除 id 字段
      return {
        type: 42,
        metaId: 42,
        resourceId: item.id,
        ...rest // 将剩余的字段添加回新的对象中
      }
    })
  }
  nestedArray.push(picture)
  nestedArray.push(video)
  nestedArray.push(audio)
  nestedArray.push(mate)
  let ss = [].concat(...nestedArray)
  resourceList.value = ss
}
const updateResource = (type, list) => {
  return list.map((item: any) => ({
    ...item,
    type: type,
    metaId: type,
    resourceId: item.id
  }))
}
/** 更新有效期 */
const addItemTime = async (status: any) => {
  if (status == '0') {
    copyrightInfoData.value.copyrightValidity = validitys.value.always
  } else {
    var startString = copyrightInfoData.value.datetime[0]
      .toLocaleDateString('zh-CN', { year: 'numeric', month: 'numeric', day: 'numeric' })
      .replace(/\//g, '/')
    var endString = copyrightInfoData.value.datetime[1]
      .toLocaleDateString('zh-CN', { year: 'numeric', month: 'numeric', day: 'numeric' })
      .replace(/\//g, '/')
    copyrightInfoData.value.copyrightValidity = startString + ' - ' + endString
  }
}
const route = useRoute()
const type = route.query.type
const id = route.query.id
const appendixButton = ref(false)
const info = async () => {
  if (id) {
    formLoading.value = true
    PropInfo.value = true
    PropButton.value = false
    try {
      copyrightInfoData.value = await CopyrightApi.getCopyright(id)
      PropInfo.value = copyrightInfoData.value.propName != '' ? true : false
      PropButton.value = copyrightInfoData.value.propName != '' ? false : true
      appendixButton.value = copyrightInfoData.value.appendix ? true : false
      if (copyrightInfoData.value.validity == '0') {
        copyrightInfoData.value.copyrightValidity = validitys.value.always
      } else {
        copyrightInfoData.value.datetime = [
          new Date(copyrightInfoData.value.copyrightValidity.split('-')[0]),
          new Date(copyrightInfoData.value.copyrightValidity.split('-')[1])
        ]
      }
      getListCopyrightStages()
      getListCopyrightResources()
    } finally {
      formLoading.value = false
    }
  }
}

/** 附件预览 */
const appendixPreview = () => {
  window.open(copyrightInfoData.value.appendix)
}
/** 商品图预览 */
const imagePreview = (args) => {
  const urlList = []
  if (isArray(args)) {
    args.forEach((item) => {
      urlList.push(item.url)
    })
  } else {
    urlList.push(args)
  }
  createImageViewer({
    urlList
  })
}

function isNumber(str: string): boolean {
  return /^\d+$/.test(str) // 只包含数字的正则表达式
}

const imaged = (row) => {
  if (!row) {
    return false
  }
  if (isNumber(row)) {
    return false
  }
  return isValidJson(row)
}
const buildImage = (name, row) => {
  if (JSON.parse(row[name]).length > 0) {
    return JSON.parse(row[name].replaceAll('\\', ''))[0].url
  } else {
    return ''
  }
}

function isValidJson(str) {
  if (str.startsWith('{') || str.startsWith('[')) {
    if (str.endsWith(']') || str.endsWith('}')) {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
  try {
    JSON.parse(str)
    return true
  } catch (e) {
    return false
  }
}
onMounted(() => {
  info()
  // handelQuery(activeName.value)
  restTabs()
})
</script>
<style lang="scss" scoped>
.eidt-row-p {
  width: 100%;
  height: 32px;
  margin: 0;
  line-height: 32px;
  text-align: center;
}

// 设置表格中输入框为边框为0
.ipt {
  width: 60px;
  height: 23px;
  margin-right: 5px;
  border: 1px solid rgb(187 187 187 / 100%);
  border-radius: 3px;
  outline: none;
}

.div-A {
  width: 45%;
  height: 200px;
}

.div-B {
  width: 50%;
  height: 200px;
}

.div-C {
  width: 50%;
  height: 200px;
}

.inline-div {
  display: inline-block;
}
</style>
